import { RouteRecordRaw } from 'vue-router'
import { IBreadcrumb } from '@/base-ui/breadcrumb'

let fristMenu: any = null //第一个菜单作为默认跳转菜单

//根据传入的菜单数据来生成对应的路由
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  // 1.先去加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = []
  //利用webpack解析该路径下的文件
  const routeFiles = require.context('../router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    //进行路径拼接得到对应路由配置对象
    const route = require('../router/main' + key.split('.')[1])
    if (route) allRoutes.push(route.default)
  })

  // 2.根据菜单获取需要添加的routes
  // userMenus:
  // type === 1 -> children -> type === 1
  // type === 2 -> url -> route
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        //子类型直接匹配使用
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) routes.push(route)
        if (!fristMenu) {
          fristMenu = menu
        }
      } else {
        //菜单项需要解析子类型 递归执行
        _recurseGetRoute(menu.children)
      }
    }
  }

  _recurseGetRoute(userMenus)

  return routes
}

//根据路由路径匹配对应菜单数据
export function pathMapToMenu(
  userMenus: any[], //全部菜单
  currentPath: string, //路由路径
  breadcrumbs?: IBreadcrumb[] //面包屑
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(
        menu.children ?? [],
        currentPath,
        breadcrumbs ?? []
      )
      if (findMenu) {
        breadcrumbs?.unshift({ name: menu.name })
        // breadcrumbs?.push({ name: findMenu.name })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      breadcrumbs?.unshift({ name: menu.name })
      return menu
    }
  }
}

//根据路由路径匹配对应面包屑
export function pathMapBreadcrumbs(userMenus: any[], currentPath: string): any {
  const breadcrumbs: IBreadcrumb[] = []
  pathMapToMenu(userMenus, currentPath, breadcrumbs)
  return breadcrumbs
}

//根据菜单获取对应编辑权限
export function mapMenusToPermissions(userMenus: any[]) {
  const permissionsa: any[] = []
  const _recurseGetPermission = (userMenus: any) => {
    for (const menu of userMenus) {
      if (menu.type == 1 || menu.type == 2) {
        _recurseGetPermission(menu.children)
      } else if (menu.type == 3) {
        permissionsa.push(menu.permission)
      }
    }
  }
  _recurseGetPermission(userMenus)
  return permissionsa
}

//根据现有的菜单数据筛选出根节点的id
export function menuMapLeafKeys(menuList: any[]) {
  const leftList: number[] = []
  const _recurseGetLeaf = (menuList: any[]) => {
    for (const item of menuList) {
      if (item.children) {
        _recurseGetLeaf(item.children)
      } else {
        leftList.push(item.id)
      }
    }
  }
  _recurseGetLeaf(menuList)
  return leftList
}

export { fristMenu }
